package com.dinero.pagecontents.activity

import android.util.Log
import android.view.KeyEvent
import androidx.navigation.fragment.NavHostFragment
import com.android.basekt.activity.BaseDataBindingActivity
import com.android.basekt.base.BaseDataBindingConfig
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ToastUtils
import com.dinero.pagecontents.R
import com.dinero.deseo.fragment.LoginInputFragment
import com.dinero.pagecontents.databinding.ActivityLoginBinding
import com.dinero.pagecontents.viewmodel.LoginViewModel

/**
 * @Created on 2021/12/11 14:41
 * @Author {"between":"-2","endf":"Please Login","tell":{}}
 * @Describe
 */
class LoginActivity : BaseDataBindingActivity<ActivityLoginBinding, LoginViewModel>() {
    override fun initView() {
    }

    override fun initData() {
        BarUtils.setStatusBarLightMode(this, true)
        mBinding.viewModel = mViewModel
        mViewModel.finishView.observe(this) {
            if (it && getFragmentSize()) {
                exitAfterTwice()
            } else if (it) {
                finishView()
            }
        }
        mViewModel.finishActivity.observe(this) {
            Log.i("LoginViewModel", "initData: " + it)
            if (it == true) {
                finish()
                System.exit(0);
            }
        }
    }

    /**
     * 获取binding相关配置
     *
     * @return
     */
    override fun getDataBindingConfig(): BaseDataBindingConfig {
        return BaseDataBindingConfig(R.layout.activity_login)
    }

    /**
     * 获取viewmodel Clazz
     *
     * @return
     */
    override fun initViewModelClazz(): Class<LoginViewModel> {
        return LoginViewModel::class.java
    }

    override fun finishView() {
        var navHostFragment: NavHostFragment =
            supportFragmentManager.findFragmentById(R.id.fragment) as NavHostFragment
        var back = navHostFragment.navController.popBackStack()
        if (!back) {
            finish()
        }
    }

    fun getFragmentSize(): Boolean {
        val navHostFragment = supportFragmentManager.fragments.first() as NavHostFragment
        var result = false
        navHostFragment.childFragmentManager.fragments.forEach {
            if (it is LoginInputFragment) {
                result = true
            }
        }
        return result
    }

    var exitTime: Long = 0;
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (getFragmentSize() && keyCode == KeyEvent.KEYCODE_BACK) {
            exitAfterTwice()
            return false
        }
        return super.onKeyDown(keyCode, event)
    }

    /**
     * 连续点击2次退出
     */
    fun exitAfterTwice() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ToastUtils.showShort("Favor de hacer click en Regresar para salir")
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }


}